/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.benchmark;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import cgl.narada.event.NBEvent;
import cgl.narada.service.client.NBEventListener;
import cgl.narada.service.client.NBRecoveryListener;
import cgl.narada.service.client.NBRecoveryNotification;
import cgl.narada.util.StatUtils;

/** 
    This class represents the subscribers of the benchmark suite. This
    benchmark client can also behave as a measuring subscriber responsible
    for computing latencies, standard deviations, system throughputs etc.
    
    @author Shrideep Pallickara 
    $Revision$
    $Date$
*/ 

public class GaugeSubscriber implements NBEventListener, NBRecoveryListener {
  
  private boolean gatherStats=false;
  private int subscriberId;
  /** This variable is set by the BenchMark process */
  private int numOfMessages=1;
  /** This variable is set by the BenchMark process */
  private int messageSize=0;
  /** This corresponds to the case being benchMarked */
  private int benchMarkTracker=0;

  /** Maintain latencies in an array - for computing mean, variance */
  private long[] latencyArray;

  /** Helps in resetting latency Arrays etc */
  private int messageTracker=0;
  
  /** Used for computing reception throughputs */
  private long subStart, subEnd;
  
  /** A buffered writer for gathering testing statistics */
  private BufferedWriter buffWrite;

  private boolean consoleOutput=false;
  
  private int[] messageSizes = {50, 100, 200, 500, 1000, 2000, 5000};
  private int messageSizeTracker=0;

  private int maxReject=0;
  private long[] maxLatencies;

  private StatUtils statUtils;
  private String moduleName = "GaugeSubscriber: ";
  
  public GaugeSubscriber(int subscriber) {
    subscriberId = subscriber;
    statUtils = new StatUtils();
    System.out.println(moduleName + "SubscriberId = " + subscriberId);
  }
  
  public void setAsMeasuringClient(String fileName, int _numOfMessages, 
				   int[] messageSizes, int maxRejects) {
    gatherStats = true;
    initializeReportFile(fileName);
    numOfMessages = _numOfMessages;
    gatherStatsForMessages(numOfMessages);
    this.messageSizes = messageSizes;
    maxReject = maxRejects;
    maxLatencies = new long[maxReject];
    System.out.println(moduleName + "Will gather stats for (" + numOfMessages+ 
		       ") Maximum Rejects =" + maxReject  );
  }
  
  public void printToConsole(boolean printInfo) {
    consoleOutput = printInfo;
  }

  private void initializeReportFile(String fileName) {
    try {
      buffWrite = new BufferedWriter(new FileWriter(new File(fileName)));
      System.out.println(moduleName + "Initialized Subscriber Report File [" + 
			 fileName + "]");
    } catch (IOException ioe) {
      System.out.println(moduleName + "Error writing file ...... ");
    } 
  }
  
  
  private void writeToReportFile(String reportLine) {
    try {
      buffWrite.write(reportLine, 0, reportLine.length());
      buffWrite.newLine();
      buffWrite.flush();
    } catch (IOException ioe) {
      System.out.println(moduleName + "Error writing file ...... ");
    } 
  }
  
  public void gatherStatsForMessages(int numMessages) {
    numOfMessages = numMessages;
    latencyArray = new long[numMessages];
  }
  
  /** The message that would be invoked by the underlying system */
  public void onEvent( NBEvent nbEvent) {
    //System.out.println(moduleName + "BMClient [" +subscriberId + "]" );
    if (gatherStats) {
      if (messageTracker ==0) {
	subStart = System.currentTimeMillis();
      }
      long publishedAt = nbEvent.getEventHeaders().getTimeStamp();
      long latency = System.currentTimeMillis() - publishedAt;
      
      latencyArray[messageTracker++] = latency;

      if (consoleOutput) {
	System.out.println(moduleName + "delay=" + latency + 
			   " for event number [" + messageTracker+"]");
      }/*consoleOutput */      

      if (messageTracker == numOfMessages) {
	reportStatistics();
      }
    } /*end if(gatherStats)*/
  }

  /** Upon completion of the attempt to recover, this method is invoked on
      the listener that was registered with the */
  public void onRecovery(NBRecoveryNotification recoveryNotification) {
    System.out.println(moduleName + recoveryNotification );
  }
  
  public void reportStatistics() {
    subEnd = System.currentTimeMillis();

    
    double meanLatency = 
      statUtils.computeMeanWithoutOutliers(latencyArray, 
					   latencyArray.length);
    
    double stdDeviation = 
      statUtils.computeStandardDeviationWithoutOutliers(latencyArray, 
							latencyArray.length);

    double receivingRate = 
      ((double)numOfMessages/(double)(subEnd-subStart))*((double)1000);
    
    benchMarkTracker++;
    messageSize = messageSizes[messageSizeTracker++];
    /** Track the message sizes being cycled through */
    if ( messageSizeTracker == messageSizes.length) {
      /** This means that the end of the array has been reached.
	  We then need to rest it back to the start i.e. 0*/
      messageSizeTracker=0;
    }
    String reportLine = messageSize + "  " + (float)meanLatency + "  " + 
      (float)stdDeviation + "   "  + (float)receivingRate + "  " +
      benchMarkTracker;
    writeToReportFile(reportLine);
    
    if (consoleOutput) {
      for (int i=0; i < maxReject; i++) {
	System.out.print(maxLatencies[i] + " ");
      } 
      printToConsole(meanLatency, stdDeviation, receivingRate);
    }
    
    /** Now lets proceed to reset the messageTracker  */
    messageTracker=0;
  }
  
  private void printToConsole(double meanLat, double deviation, double rRate) {
    StringBuffer buff = new StringBuffer();
    buff.append("End of TestCase " + benchMarkTracker);
    buff.append("\nThe individual messages had a payload of size " +
		messageSize);
    buff.append("\nThe mean for (" + messageTracker + 
		") messages is " + meanLat + "mSecs");
    buff.append("\nThe Standard Deviation for this sample of messages is " +
		deviation);
    buff.append("\nThe messages were received at a rate of " + 
		rRate + " messages/Sec \n");
    System.out.println(moduleName + buff);
  }


  public static void main(String[] args) {
    
  }


}

